package com.example.com.daervideo.vm;

import android.app.Activity;
import android.content.Context;
import android.databinding.Bindable;
import android.databinding.Observable;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableInt;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;


import com.example.com.daervideo.activitys.MainActivity;
import com.example.com.daervideo.activitys.loginRegist.ForgetAndResetPassword;
import com.example.com.daervideo.activitys.loginRegist.LoginActivity;
import com.example.com.daervideo.activitys.loginRegist.ProtocolActivity;
import com.example.com.daervideo.activitys.loginRegist.RegistActivity;
import com.example.com.daervideo.databinding.ActivityLoginBinding;

import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.utils.DESUtils;
import com.example.com.daervideo.utils.MD5Utils;
import com.example.com.daervideo.utils.RetrofitClient;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.Disposable;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/11/21.
 */

public class LoginViewModel extends BaseViewModel {
    private final LoginViewModel that;
    private final ApiService apiService;
    public String text = "abc";
    private final LoginActivity loginActivity;
    private int time = 60;
    private final MainHandler handler;
    ActivityLoginBinding binding;
    public ObservableBoolean isCode = new ObservableBoolean(false);

    public LoginViewModel(Context context) {
        super(context);
        loginActivity = (LoginActivity) context;
        this.that = this;
        binding = loginActivity.getBinding();
        apiService = RetrofitClient.getInstance().create(ApiService.class);
        handler = new MainHandler(context);
    }

    public BindingCommand login = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            boolean checked = binding.protocolButton.isChecked();
            if (!checked) {
                ToastUtils.showShort("请仔细阅读协议！");
                return;
            }
            String phone = binding.phone.getText().toString().trim();
            String password = binding.inputPassword.passwordEditText.getText().toString().trim();
            String code = binding.code.getText().toString().trim();
            if (phone.length() != 11) {
                ToastUtils.showShort("手机号码填写有误！");
                return;
            }
            if (StringUtils.isEmpty(password) && StringUtils.isEmpty(code)) {
                ToastUtils.showShort("填写有误！");
            }
            String md5Password = null;
            if (!StringUtils.isTrimEmpty(password)) {
                md5Password = DESUtils.utilEncode(password);
            }

            apiService.login(phone, md5Password, code)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse>() {
                        @Override
                        public void accept(BaseResponse response) throws Exception {
                            dismissDialog();
                            if (response.getCode() == 0) {
                                startActivity(MainActivity.class);
                                SPUtils.getInstance().put("isFirst", false);
                                loginActivity.finish();
                            } else {
                                ToastUtils.showShort(response.getMsg());
                            }
                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();
                        }
                    });

        }
    });

    public BindingCommand toRegist = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(RegistActivity.class);
        }
    });
    public BindingCommand showmima = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            that.isCode.set(false);
        }
    });

    public BindingCommand showCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            that.isCode.set(true);
        }
    });

    public BindingCommand protocol = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(ProtocolActivity.class);
        }
    });

    public BindingCommand forgetpassword = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(ForgetAndResetPassword.class);
        }
    });


    public BindingCommand getCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            String phone = binding.phone.getText().toString().trim();
            if (StringUtils.isEmpty(phone) && phone.length() != 11) {
                ToastUtils.showShort("手机号码有误");
                return;
            }

            binding.buttonCode.setClickable(false);

            apiService.sendLoginCode(phone)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse>() {
                        @Override
                        public void accept(BaseResponse response) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(response.getMsg());
                            if (response.getCode() == 0) {
                                Message message = handler.obtainMessage(1);     // Message
                                handler.sendMessageDelayed(message, 1000);
                            } else {
                                binding.buttonCode.setClickable(true);
                            }

                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();

                            binding.buttonCode.setClickable(true);
                        }
                    });
        }
    });

    private class MainHandler extends Handler {
        private final WeakReference<Context> reference;

        public MainHandler(Context activity) {
            reference = new WeakReference<Context>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Context activity = reference.get();
            if (activity != null) {
                time--;
                binding.buttonCode.setText(time + "s");
                if (time > 0) {
                    Message message = handler.obtainMessage(1);
                    handler.sendMessageDelayed(message, 1000);      // send message
                } else {

                    binding.buttonCode.setClickable(true);
                    binding.buttonCode.setText("获取验证码");
                    time = 60;
                }
            }
            super.handleMessage(msg);
        }
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
